﻿using Microsoft.Office.Interop.Word;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace WeekReport
{

    public partial class FormWeekReport : Form
    {
        private string iniFile = (Directory.GetCurrentDirectory() + @"\config.ini");
        private object missing =  Missing.Value;
        private Microsoft.Office.Interop.Word.Application word;

        public FormWeekReport()
        {
            this.InitializeComponent();
            this.buttonOK.DialogResult = DialogResult.OK;
            this.buttonCancel.DialogResult = DialogResult.Cancel;
            base.AutoScaleMode = AutoScaleMode.Font;
        }

        private object FindData(Document doc, string title, bool forward)
        {
            Range content = doc.Content;
            object findText = (object)title;
            object finddirection = (object)forward;
         
            content.Find.ClearFormatting();
            if (content.Find.Execute(ref findText, ref this.missing, ref this.missing, ref this.missing
                , ref this.missing, ref this.missing, ref finddirection, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing))
            {
                return (object)content;
            }

            return null;
        }

        private void AddData(Document doc, string title,bool forward)
        {
            object range = FindData(doc, "工作体会：", forward); 
            if (range==null)
            {
                return;
            }
            doc.Bookmarks.Add(title, ref range);
        }

        private void AddBookMarks(Document doc, Array arrHeadings)
        {
            foreach (Bookmark bookmark in doc.Bookmarks)
            {
                bookmark.Delete();
            }
            char[] chArray = new char[] { Convert.ToChar(0x70), Convert.ToChar(0x20) };
            foreach (object obj2 in arrHeadings)
            {
                string strTitle = obj2.ToString().Trim();
                try
                {
                    object findText = strTitle.Substring(2);
                    Range content = doc.Content;
                    content.Find.ClearFormatting();
                    if (content.Find.Execute(ref findText, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing))
                    {
                        object range = content;
                        doc.Bookmarks.Add(this.GetBookMark(findText.ToString()), ref range);
                    }
                }
                catch (Exception)
                {
                }
            }
            AddData(doc,"微博", false);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            base.Close();
            Environment.Exit(0);
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.word = new ApplicationClass();
            this.word.Visible = false;
            WritePrivateProfileString("info", "dest", this.textBoxPath.Text, this.iniFile);
            string[] desp = new string[] { this.textBoxContent.Text, this.textBoxTime.Text };
            this.SaveHeader(this.GetTitle(), desp);
            this.word.Quit(ref this.missing, ref this.missing, ref this.missing);
            this.CallWeekRep("weekrep.exe", this.textBoxPath.Text);
        }

        private void CallWeekRep(string executefile, string file)
        {
            Process process = new Process();
            process.StartInfo.FileName = Directory.GetCurrentDirectory() + @"\" + executefile;
            process.Start();
            process.WaitForExit();
            this.ChangeDocument(file);
        }

        private  void ChangeDocument(string destfile)
        {
            this.word = new ApplicationClass();
            this.word.Visible = false;
            StringBuilder retVal = new StringBuilder(0x100);
            GetPrivateProfileString("info", "srcdir ", "", retVal, retVal.Capacity, this.iniFile);
            if (retVal.Length != 0)
            {
                retVal.Append(@"\");
                retVal.Append(destfile);
                object file = retVal.ToString();
                Document doc = this.OpenDocument(ref file);
                if (doc != null)
                {
                    object wdRefTypeHeading = WdReferenceType.wdRefTypeHeading;
                    Array crossReferenceItems = (Array) doc.GetCrossReferenceItems(ref wdRefTypeHeading);
                    this.AddBookMarks(doc, crossReferenceItems);
                    for (int i = 1; i <= doc.Hyperlinks.Count; i++)
                    {
                        object obj4 = i;
                        Hyperlink link = doc.Hyperlinks.get_Item(ref obj4);
                        object obj5 = this.IsTitleExist(link, ref crossReferenceItems);
                        if (obj5 != null  )
                        {
                            try
                            {
                                link.Address = "#";
                                link.SubAddress = this.GetBookMark(obj5.ToString().Trim().Substring(2));
                            }
                            catch (Exception)
                            {
                            }
                        }
                        else if (link.TextToDisplay.Contains("微博"))
                        {
                             try
                            {
                                link.Address = "#";
                                link.SubAddress = this.GetBookMark("微博");
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    object savechanges = true;
                    this.CloseDocument(ref doc, ref savechanges);
                    this.word.Quit(ref this.missing, ref this.missing, ref this.missing);
                }
            }
        }

        private void CloseDocument(ref Document doc, ref object savechanges)
        {
            try
            {
                doc.Close(ref savechanges, ref this.missing, ref this.missing);
            }
            catch (Exception)
            {
            }
        }

        private void dateTimeChanged(object sender, EventArgs e)
        {
            this.UpdatePath();
        }
        private string GetBookMark(string strBookmark)
        {
            int startIndex = strBookmark.LastIndexOf('(');
            if (startIndex >= 0)
            {
                strBookmark = strBookmark.Remove(startIndex);
            }
            return strBookmark;
        }

        private object GetHeaderPath()
        {
            StringBuilder retVal = new StringBuilder(0x100);
            GetPrivateProfileString("info", "homepage ", "", retVal, retVal.Capacity, this.iniFile);
            return retVal.ToString();
        }

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        private string GetTitle()
        {
            return (this.beginDateTime.Value.ToString("yyyy年MM月dd日") + " ~ " + this.endDateTime.Value.ToString("yyyy年MM月dd日") + "\r\n");
        }


        private object IsTitleExist(Hyperlink link, ref Array arrHeadings)
        {
            foreach (object obj2 in arrHeadings)
            {
                if (obj2.ToString().Contains(link.TextToDisplay))
                {
                    return obj2;
                }
            }
            return null;
        }

        private void LoadTaskDescription()
        {
            StringBuilder retVal = new StringBuilder(0x100);
            GetPrivateProfileString("info", "homepage ", "", retVal, retVal.Capacity, this.iniFile);
            object savechanges = false;
            try
            {
                object file = retVal.ToString();
                Document doc = this.OpenDocument(ref file);
                if (doc != null)
                {
                     
                    this.textBoxContent.Text = doc.Tables[1].Cell(1, 3).Range.Text.TrimEnd("\r\a".ToCharArray());
                    this.textBoxContent.Text = this.textBoxContent.Text.Replace("\r", Environment.NewLine);
                    this.textBoxTime.Text = doc.Tables[1].Cell(2, 3).Range.Text.TrimEnd("\r\a".ToCharArray());
                    this.CloseDocument(ref doc, ref savechanges);
                }
            }
            catch (Exception)
            {
            }
        }

        private void OnFormClose(object sender, FormClosedEventArgs e)
        {

        }

        private void OnFormLoad(object sender, EventArgs e)
        {
            this.word = new ApplicationClass();
            this.word.Visible = false;
            this.LoadTaskDescription();
            this.comboProject.SelectedIndex = 0;
            this.word.Quit(ref this.missing, ref this.missing, ref this.missing);
            this.UpdatePath();
        }

        private Document OpenDocument(ref object file)
        {
            Document document = null;
            try
            {
                document = this.word.Documents.Open(ref file, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing);
            }
            catch (Exception)
            {
            }
            return document;
        }

        private void SaveHeader(string title, string[] desp)
        {
            object headerPath = this.GetHeaderPath();
            Document doc = this.OpenDocument(ref headerPath);
            if (doc != null)
            {
                try
                {
                    string str = "时间：";
                    object unit = 1;
                    object length = str.Length;
                    doc.Paragraphs[2].Range.Select();
                    this.word.Selection.MoveStart(ref unit, ref length);
                    this.word.Selection.Range.Text = title;
                    this.SaveTaskDescription(doc.Tables[1], ref desp);
                }
                catch (Exception)
                {
                }
                object savechanges = true;
                this.CloseDocument(ref doc, ref savechanges);
            }
        }

        private void SaveTaskDescription(Table table, ref string[] desp)
        {
            table.Cell(1, 3).Range.Text = desp[0].ToString();
            table.Cell(2, 3).Range.Text = desp[1].ToString();
        }

        private void UpdatePath()
        {
            string str = this.beginDateTime.Value.ToString("yyyyMMdd");
            string str2 = this.endDateTime.Value.ToString("yyyyMMdd");
            this.textBoxPath.Text = this.comboProject.SelectedItem.ToString() + "周工作报告" + str + "-" + str2 + ".doc";
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        public class EventArgsEx : EventArgs
        {
            public string str;
        }


    }
}

